package xyz.longicorn.driver.controller;

import lombok.SneakyThrows;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import xyz.longicorn.driver.pojo.FileInfo;
import xyz.longicorn.driver.service.FileService;
import xyz.longicorn.driver.util.FileUtils;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;

// 根据文件生成预览
@Controller
@RestController
@RequestMapping("/picture")
public class PreviewController {
    @Resource
    private FileService fileService;

    // 生成缩略图
    @SneakyThrows
    @RequestMapping("/thumb")
    public void thumb(HttpServletResponse resp, String hash) {
        String path = this.preHandle(resp, hash); // 获取要处理的图片路径
        if (path == null) return;
        // 设置输出头
        resp.addHeader("Content-Type", "image/jpeg");
        FileUtils.getImagePreview(path, resp.getOutputStream());
    }

    // 生成预览图
    @SneakyThrows
    @RequestMapping("/preview")
    public void preview(HttpServletResponse resp, String hash) {
        String path = this.preHandle(resp, hash);
        if (path == null) return;

        final ServletOutputStream os = resp.getOutputStream(); // 获取网络输出流
        FileInputStream is = new FileInputStream(path); // 获取文件输入流

        byte[] bytes = new byte[10240];
        int len;
        while ((len = is.read(bytes)) != -1) {
            os.write(bytes, 0, len);
        }
        os.close();
        is.close();

    }

    /**
     * 通过hash获取图片的真是路径
     * @param resp
     * @param hash
     * @return
     */
    @SneakyThrows
    private String preHandle(HttpServletResponse resp, String hash) {
        FileInfo info = fileService.getByMd5(hash); // 查询文件信息
        if (null == info) { // 文件不存在
            resp.getWriter().println("file not found!");
            return null;
        }
        if (!FileUtils.isImage(info.getType())) { //判断是否是图片
            resp.getWriter().println("file can not preview!");
            return null;
        }
        if (info.getPath().startsWith("http")) {
            // 远程文件直接跳转
            resp.sendRedirect(info.getPath());
            return null;
        }
        return info.getPath();
    }
}
